//
//  WBOauthView.swift
//  SinaWeibo_Swift
//
//  Created by TianZhen on 16/4/9.
//  Copyright © 2016年 TianZhen. All rights reserved.
//
import SVProgressHUD
import UIKit

class WBOauthViewController : UIViewController {

    lazy var webView = UIWebView()
    
    override func loadView() {
        super.loadView()
        // 重新复制自己的view
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 添加右边按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
        
        // 添加左边按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("fill"))
        
        title = "新浪微博"
        
        // 请求url
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        
        // 加载授权界面
        webView.loadRequest(NSURLRequest(URL: NSURL(string: urlString)!))
    }
    
    // tabbarItem 取消
    @objc private func cancel()
    {
        self.navigationController?.dismissViewControllerAnimated(true, completion: { () -> Void in
        })
    }
    
    // tabbarItem 填充
    @objc private func fill()
    {
        print(__FUNCTION__)
    }
}

// 实现 webView 的代理方法
extension WBOauthViewController: UIWebViewDelegate
{
    // 当开始加载请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 拿到 URL 绝对路径
        let urlString = request.URL!.absoluteString
        
        if !urlString.hasPrefix(redirect_uri)
        {
            return true
        }
        print("回调地址:\(request.URL?.query)")
        
        // 判断后面时候有参数
        if let query = request.URL?.query
        {
            let nsQuery = query as NSString
            let codeString = "code="
            
            // 判断query里面是否包含code=字符串
            if nsQuery.hasPrefix(codeString)
            {
                let code = nsQuery.substringFromIndex(codeString.characters.count)
                // 模型不需要关心怎么加载和保存AccessToken
                WBUserAccountViewModel.sharedInstance.loadAccessToken(code, loadAccessTokenCallback: { (error) -> () in
                    
                    if error != nil
                    {
                        // 加载出错
                        SVProgressHUD.showErrorWithStatus("网络不给力")
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1), dispatch_get_main_queue()!, { () -> Void in
                            
                            self.close() // 关闭
                        })
                    }
                    // 直接关闭控制器
                    print("加载accessToken完成")
                    // 切换界面
                    (UIApplication.sharedApplication().delegate as? AppDelegate)?.switchViewController(false)
                    
                    self.close()
                })
            }else
            {           // 点击取消
                print("点击取消")
                self.close()
            }
        }
        
        return false
    }
    
    func close()
    {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true) { () -> Void in
        }
    }
    
    // 当加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
}
